#!/usr/bin/env python 
# -*- coding: utf-8 -*-
# @Time    : 2018/12/3 9:18
# @Author  : Tang Yang
# @Desc    : 
# @File    : context.py
import os
from src.detection.utils.detector import load_model
# from sklearn.externals import joblib
# from tensorflow.keras.applications import VGG19
# from tensorflow.keras.models import Model
import xml.etree.ElementTree as ET
from src.utils.custom_exception import ConfigParseError


class Config:
    def __init__(self, config_path):
        self._checkpoint_dir = None
        self._pbtxt_file_dir = None
        self._confidence = None
        self._config_path = config_path
        self._pca_parameters_path = None
        self._parse_xml()

    def _parse_xml(self):
        if not os.path.exists(self._config_path):
            raise FileNotFoundError(self._config_path + " Not Found!")
        try:
            tree = ET.parse(self._config_path)
            root = tree.getroot()
            self._checkpoint_dir = root.find("checkpoint_dir").text
            self._pbtxt_file_dir = root.find("pbtxt_file_dir").text
            self._confidence = float(root.find("confidence").text)
            # self._pca_parameters_path = root.find("pca_parameters").text
            self._stitching_max_working_size = int(root.find("stitching_max_size").text)
        except BaseException:
            raise ConfigParseError()

    @property
    def stitching_max_working_size(self):
        return self._stitching_max_working_size

    @property
    def checkpoint_dir(self):
        return self._checkpoint_dir

    @property
    def pbtxt_file_dir(self):
        return self._pbtxt_file_dir

    @property
    def confidence(self):
        return self._confidence

    @property
    def pca_parameters_path(self):
        return self._pca_parameters_path


class Context:
    def __init__(self, config_file):
        self._config = Config(config_file)
        self._detection_graph_list = []
        self._label_class_path_list = []
        self.__load_model_and_label_file()
        self._vgg_model = None
        self._joblib = None
        self._layer = None
        self._shape = None
        # self.__load_vgg_model()

    # def __load_vgg_model(self):
    #     self._shape = (128, 128, 3)
    #     self._layer = 'block4_conv4'
    #     base_model = VGG19(weights='imagenet', include_top=False, input_shape=self._shape)
    #     self._vgg_model = Model(inputs=base_model.input, outputs=base_model.get_layer(self._layer).output)
    #     self._joblib = joblib.load(self._config.pca_parameters_path)

    def __load_model_and_label_file(self):
        for detection_graph in os.listdir(self._config.checkpoint_dir):
            detection_name = os.path.join(self._config.checkpoint_dir, detection_graph)
            detection_graph = load_model(detection_name)
            self._detection_graph_list.append(detection_graph)
            model_name = detection_name.split('_')[-1].split('.')[0]
            # assert detection_graph==start_time
            # 找对应的pdtxt
            for label_name in os.listdir(self._config.pbtxt_file_dir):
                if model_name in label_name:
                    label_class_name = os.path.join(self._config.pbtxt_file_dir, label_name)
                    self._label_class_path_list.append(label_class_name)
                    break

    @property
    def detection_graph_list(self):
        return self._detection_graph_list

    @property
    def label_class_path_list(self):
        return self._label_class_path_list

    @property
    def shape(self):
        return self._shape

    @property
    def layer(self):
        return self._layer

    @property
    def vgg_model(self):
        return self._vgg_model

    @property
    def joblib(self):
        return self._joblib

    @property
    def confidence(self):
        return self._config.confidence

    @property
    def working_size(self):
        return self._config.stitching_max_working_size

